package com.example.reserveseat.Scheduled;


import com.example.reserveseat.Enums.ReserveAreaEnum;
import com.example.reserveseat.Enums.ReserveStrategyEnum;
import com.example.reserveseat.Enums.ResponseStatusEnum;
import com.example.reserveseat.GateWay.ScheduledGateWay;
import com.example.reserveseat.Object.*;
import com.example.reserveseat.Object.*;
import com.example.reserveseat.Utils.TimeUtil;
import jakarta.annotation.Resource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;


import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class reserveSeat {

    @Resource
    private ScheduledGateWay scheduledGateWay;

    @Value("${strategy}")
    private String strategy;

    @Value("${start}")
    private String start;

    @Value("${end}")
    private String end;


//    @Scheduled(fixedRate = 5000)
    public void printCurrentTime() {
        //1.查询信息
        AllAreaSeateInfo allAreaSeateInfo = new AllAreaSeateInfo();
        ReservationResponse reservationResponseOne = scheduledGateWay.queryInfo(ReserveAreaEnum.CALM_ONE.getValue(), LocalDate.now());
        if (Objects.isNull(reservationResponseOne)) {
            throw new RuntimeException("返回参数参数错误");
        }
        allAreaSeateInfo.setAreaOneList(reservationResponseOne.getData());

        ReservationResponse reservationResponseTwo = scheduledGateWay.queryInfo(ReserveAreaEnum.CALM_TWO.getValue(), LocalDate.now());
        if (Objects.isNull(reservationResponseTwo)) {
            throw new RuntimeException("返回参数参数错误");
        }
        allAreaSeateInfo.setAreaTwoList(reservationResponseTwo.getData());


        ReservationResponse reservationResponseTHRee = scheduledGateWay.queryInfo(ReserveAreaEnum.LEISURE.getValue(), LocalDate.now());
        if (Objects.isNull(reservationResponseTHRee)) {
            throw new RuntimeException("返回参数参数错误");
        }
        allAreaSeateInfo.setAreaThreeList(reservationResponseTHRee.getData());

        List<String> hours = TimeUtil.test(start, end);
        System.out.println("预约准备阶段，预约时间段为以下");
        for (String hour : hours) {
            System.out.println(hour);
        }
        System.out.println("-----------------------");
        //2.按照策略筛选信息
        ReserveStrategyEnum strategyValue = ReserveStrategyEnum.getEnumByType(strategy);
        switch (strategyValue) {
            case RANDOM:
                //1.优先沉静12区
                List<SeatData> firstMatchSeate = new ArrayList<>();
                if (!CollectionUtils.isEmpty(allAreaSeateInfo.getAreaOneList())) {
                    firstMatchSeate.addAll(allAreaSeateInfo.getAreaOneList());
                }
                if (!CollectionUtils.isEmpty(allAreaSeateInfo.getAreaTwoList())) {
                    firstMatchSeate.addAll(allAreaSeateInfo.getAreaTwoList());
                }
                randomReserve(firstMatchSeate, hours);
                if (hours.isEmpty()) {
                    System.out.println("所有待预约时间段以预约完毕");
                    return;
                }

                //2.再休闲区
                List<SeatData> secondMatch = new ArrayList<>(allAreaSeateInfo.getAreaThreeList());
                randomReserve(secondMatch, hours);
                if (hours.isEmpty()) {
                    System.out.println("所有待预约时间段以预约完毕");
                    return;
                } else {
                    System.out.println("以下时间段没被预约到");
                    for (String hour : hours) {
                        System.out.println(hour);
                    }
                }
                break;
            default:
                throw new RuntimeException("没有此决策实现过程");
        }
    }

    public boolean generationOrder(OrderInfo orderInfo) {
        // 进行第一次获取模板List
        ListResponse listResponse1 = scheduledGateWay.getList(3,"E0CB55F8F3F9CD5D95A96A16039A6616");
        if (Objects.isNull(listResponse1)) {
            throw new RuntimeException("第一次请求getList接口返回参数错误");
        }
        List<String> stringList = listResponse1.getData();
        //收集list接口返回的data数组
        List<String> data = new ArrayList<>();
        for (String s : stringList) {
            data.add(s+"");
        }
        // 调用请求预约接口
        PreOrderResponse preOrderResponse = scheduledGateWay.preOrder(orderInfo);
        if (Objects.isNull(preOrderResponse)) {
            throw new RuntimeException("preOrder接口返回参数错误");
        }
        PreSeatInfo seatInfo = preOrderResponse.getData();
        if (seatInfo.is_reservable()) {
            // 获取紧急联系人
            MemberInfoResponse memberInfoResponse = scheduledGateWay.getMemberInfo();
            if (Objects.isNull(memberInfoResponse)) {
                throw new RuntimeException("getMemberInfo接口返回参数错误");
            }
            if(!memberInfoResponse.getStatus().equals(ResponseStatusEnum.SUCCESS.getValue())){
                throw new RuntimeException("getMemberInfo接口返回参数错误");
            }
            // 进行第二次获取模板List
            ListResponse listResponse2 = scheduledGateWay.getList(4,"EC2FAB8D69354C8BB0043BFF3BC9C6B2");
            if (Objects.isNull(listResponse2)) {
                throw new RuntimeException("第二次请求getList接口返回参数错误");
            }
            List<String> stringList1 = listResponse2.getData();
            // 将两次请求获取的string数组收集起来
            for (String s : stringList1) {
                data.add(s+"");
            }
            // 座位预约
            GenerateOrderResponse generateOrderResponse = scheduledGateWay.generateOrder(orderInfo, data);
            if(ResponseStatusEnum.SUCCESS.getValue().equals(generateOrderResponse.getStatus())){
                return true;
            }

        }

        return false;
    }


    /**
     * 实现随机预约功能
     * @param seatDataList 座位信息
     * @param hours 预约时间列表
     * @return 待预约数据
     */
    public void  randomReserve(List<SeatData> seatDataList, List<String> hours) {
        if (CollectionUtils.isEmpty(seatDataList)) {
            System.out.println("没找到数据");
            return ;
        }
        //先查找是否完全匹配数据
        for (SeatData oneTwoSeate : seatDataList) {
            if (oneTwoSeate.canMatchAll(hours)) {
                System.out.println("沉静一二区筛选命中以下数据");
                for (String hour : hours) {
                    System.out.println(hour);
                }
                System.out.println("-----------------------");
                CreateInfo(hours, oneTwoSeate);
                //如果到这里完全匹配上，那就结束了
                hours.clear();
                return ;
            }
        }

        //如果没有匹配上的话，只能乱来了，从头开始找，找到一个是一个
        for (SeatData oneTwoSeate : seatDataList) {
            List<String> canReserveList = oneTwoSeate.getCanReservableHours().stream().filter(hours::contains).toList();
            if (canReserveList.isEmpty()) {
                continue;
            }
             CreateInfo(canReserveList, oneTwoSeate);
        }
        return ;
    }

    private void CreateInfo(List<String> hours, SeatData oneTwoSeate) {
        List<String> result = new ArrayList<>(hours);
        Iterator<String> iterator = hours.iterator();
        while (iterator.hasNext()) {
            String hour = iterator.next();
            OrderInfo orderInfo = new OrderInfo();
            orderInfo.setSeatId(oneTwoSeate.getSeat_id());
            orderInfo.setAreaId(oneTwoSeate.getArea_id());
            orderInfo.setStartTime(hour);
            orderInfo.setEndTime(TimeUtil.TimeDelayOneHour(hour));
            generationOrder(orderInfo);
            System.out.println("成功请求预定，预定区域：" + oneTwoSeate.getArea_id() + "区域，预定座位：" + oneTwoSeate.getSeat_id() + "号座位，预定开始时间" + hour);
            result.remove(hour); // 使用迭代器的remove方法
        }
        hours= result;
    }
}
